package edu.nf.ch02.common;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import java.io.InputStream;

/**
 * @author wangl
 * @date 2025/9/4
 * 封装Minio的API操作
 */
public class MinioOptions {

    private MinioClient client;
    private String bucket;

    public MinioOptions(MinioClient client, String bucket) {
        this.client = client;
        this.bucket = bucket;
        initBucket();
    }

    /**
     * 文件上传
     * @param path
     * @param contentType
     * @param size
     * @param input
     */
    public void upload(String path,
                       String contentType,
                       long size,
                       InputStream input) {
        try {
            client.putObject(PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(path)
                    .contentType(contentType)
                    .stream(input, size, -1)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException("Upload fail.", e);
        }
    }

    /**
     * 初始化桶
     */
    private void initBucket() {
        try {
            if(!client.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucket).build())){
                client.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            }
        } catch (Exception e) {
            throw new RuntimeException("Create bucket fail.", e);
        }
    }
}